class DDog(object):
    def __init__(self):
        print('init 方法')

    def __del__(self):
        print('del 方法')

    def __str__(self):
        print('str 方法')
        return 'Str 方法'

    def __new__(cls, *args, **kwargs):
        #会先调用 new创建 再调用init
        print('new 方法')
        return object.__new__(cls)


'''
 使用DDog()时，会做3件事
 1.调用_new_方法
 2.再调用_init_
 3.返回对象的引用
'''
dog = DDog()



'''
单例模式 重写new方法就可以
'''

class Single(object):
    #声明一个类属性
    _instance = None
    def __new__(cls, *args, **kwargs):
        if cls._instance == None:
            cls._instance = object.__new__(cls)
            return cls._instance
        else:
            return cls._instance
#创建时都是 同一个对象
obj1 = Single()
print(obj1)
obj2 = Single()
print(obj2)

#单例创建的两种形式 带参
class Single2(object):
    #声明一个类属性
    _instance = None
    def __new__(cls,name, *args, **kwargs):
        if cls._instance == None:
            cls._instance = object.__new__(cls)
            return cls._instance
        else:
            return cls._instance
    def __init__(self,name):
        self.name = name
#创建时都是 同一个对象
objj1 = Single2('MeiMei')
print(objj1)
print(objj1.name)
objj2 = Single2('HH')
print(objj2)
print(objj2.name)

